package cn.gok.intercepter;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
    自定定义Spring mvc拦截器
 */
public class TestInterceptor implements HandlerInterceptor {

    /**
     preHandle : 在Controller请求调用之前被执行，
                  如果当前方法返回为true，则表示请求可以继续向下调用，否则被拦截

     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        String userName = (String) request.getSession().getAttribute("userName");
        if ("zhangsan".equals(userName)){
            return true;
        }

        response.sendRedirect("fail.html");
        return false;
    }

    /**
        postHandle 在Controller方法向外返回结果的时候，进行拦截处理。
                    可以获取到返回的modelAndView对象
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws Exception {
        Map<String, Object> model = modelAndView.getModel();
        System.out.println("model :" + model);
        modelAndView.addObject("newValue","20221117");
    }

    /**
        afterCompletion： 当把结果发送给前端以后，调用此方法进行资源释放等收尾工作
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) throws Exception {
        System.out.println("afterCompletion run...");
    }
}
